<template>
  <div id="dialogAdPosition">
    <el-dialog
      class="about-set"
      :title="isAdd ? `添加广告位` : '编辑广告位'"
      :visible.sync="dialogData.isShow"
      width="580px"
      :before-close="labelHandleClose"
    >
      <div class="form-box">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-form-item label="显示终端" prop="terminalType">
            <el-radio-group
              class="radioGroup"
              v-model="ruleForm.terminalType"
              @change="handleChangeTerminalType"
            >
              <el-radio
                v-for="item in terminalTypeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="位置" prop="locationType">
            <el-select
              popper-class="position"
              v-model="ruleForm.locationType"
              clearable
            >
              <el-option
                v-for="item in showLocationList"
                :key="item.dictValue"
                :label="`${item.dictValue}     ${item.remark}`"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              show-word-limit
              maxlength="20"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.terminalType === 'APP'"
            label="课程"
            prop="courseType"
          >
            <el-select popper-class="position" v-model="ruleForm.courseType">
              <el-option
                v-for="item in courseTypeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- h5标签才会出现的频道号 -->
          <el-form-item
            label="频道号"
            prop="channelIds"
            v-if="isShowChannelIds"
          >
            <el-input
              v-model.trim="ruleForm.channelIds"
              show-word-limit
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="
              ruleForm.terminalType === 'APP' &&
                ruleForm.courseType === 'EXPERIENCE'
            "
            label="学院"
            prop="collegeId"
          >
            <el-select
              popper-class="position"
              multiple
              v-model="ruleForm.collegeId"
            >
              <el-option
                v-for="item in collegeList"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model.trim="ruleForm.description"
              placeholder=""
              type="textarea"
              show-word-limit
              maxlength="50"
            ></el-input>
          </el-form-item>
          <el-row type="flex">
            <el-col>
              <el-form-item class="min-margin" label="图片" prop="imgInfo">
                <uploadSingImg
                  :imgUrl="ruleForm.imgInfo"
                  accept=".jpg,.jpeg,.png,.gif"
                  :maxSize="5"
                  @getImgUrl="getImgUrl"
                >
                  <template v-slot:imgInfo
                    >（根据前台UI图尺寸，限制上传5M以内）</template
                  >
                </uploadSingImg>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                class="min-margin"
                label="弹窗"
                v-if="ruleForm.terminalType === 'H5'"
              >
                <uploadSingImg
                  :imgUrl="ruleForm.imgPopup"
                  accept=".jpg,.jpeg,.png,.gif"
                  :maxSize="5"
                  @getImgUrl="getOpenerUrl"
                >
                  <template v-slot:imgInfo
                    >（根据前台UI图尺寸，限制上传5M以内）</template
                  >
                </uploadSingImg>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="详情链接" prop="url">
            <el-input
              placeholder=""
              v-model.trim="ruleForm.url"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  add,
  edit,
  getDetail
} from '@/api/spaceConfiguration/advertisingPosition' // 接口
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import { sysNormalDisable } from '@utils/dictionariesFunc'
import { validateSpecial } from '@utils/validate'
export default {
  name: 'DialogAddEdit',
  msg: '配置标签分类-新增/编辑弹窗',
  props: ['dialogData'],
  components: {
    uploadSingImg
  },
  data() {
    const valiAppNmae = (rule, value, callback) => {
      if (!validateSpecial(value)) {
        callback(new Error('不能使用特殊字符'))
      } else {
        callback()
      }
    }
    const valiChannelIds = (rule, value, callback) => {
      // 正则表格去除空格 中文逗号转成英文逗号,去除字符转末尾的逗号
      let channelIds = value
        .replace(/，/gi, ',')
        .replace(/\s*/g, '')
        .replace(/,$/gi, '')
        .replace(/[^0-9\,]/g, '')
      this.ruleForm.channelIds = channelIds
      const channelIdsLength = this.ruleForm.channelIds.split(',').length - 1
      if (channelIdsLength > 9) {
        callback(new Error('频道号最多输入10个'))
      } else {
        callback()
      }
    }
    return {
      isAdd: true, // 新增-true,编辑-false
      loading: false,
      id: '',
      locationType: '',
      firstEnter: false,
      // 显示终端
      terminalTypeList: [],
      // 位置
      showLocationList: [], // 位置(展示列表)
      allLocationList: [], // 位置(全部列表)
      pcLocationList: [], // 终端为pc的位置列表(A1/A2)
      h5LocationList: [], // 终端为H5的位置列表(c1/c2)
      appLocationList: [], // 终端为APP的位置列表
      defaultList: [
        { dictLabel: '请选择位置', dictValue: '请选择位置', remark: '' }
      ],
      courseTypeList: [
        {
          dictLabel: '体验课',
          dictValue: 'EXPERIENCE'
        },
        {
          dictLabel: '正式课',
          dictValue: 'FORMAL'
        }
      ],
      collegeList: [], // 学院列表
      ruleForm: {
        terminalType: '', // 显示终端
        locationType: '', // 位置
        courseType: 'EXPERIENCE', // 课程类型
        name: '', // 名称
        channelIds: '',
        description: '', // 描述
        imgInfo: '', // 图片
        imgPopup: '',
        url: '' // 详情链接
      },
      rules: {
        terminalType: {
          required: true,
          message: '显示终端不能为空',
          trigger: 'blur'
        },
        locationType: {
          required: true,
          message: '位置不能为空',
          trigger: 'blur'
        },
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { validator: valiAppNmae, trigger: 'blur' }
        ],
        imgInfo: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
        url: {
          required: false,
          pattern:
            '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
          message: '请输入正确的详情链接url',
          trigger: 'blur'
        },
        collegeId: [
          { required: true, message: '请选择学院', trigger: 'change' }
        ],
        channelIds: [
          { required: true, message: '请填写频道号', trigger: 'blur' },
          { validator: valiChannelIds, trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'ruleForm.terminalType': {
      handler(newV, oldV) {
        if (newV === 'H5') {
          this.showLocationList = this.h5LocationList
        } else if (newV === 'APP') {
          this.showLocationList = this.appLocationList
        } else {
          this.showLocationList = this.pcLocationList
        }
        if (this.firstEnter) {
          this.locationType = this.ruleForm.locationType
          this.firstEnter = false
        } else {
          const isCopy = this.showLocationList.some((item) => {
            return item.dictValue === this.locationType
          })
          if (!isCopy) {
            this.ruleForm.locationType = this.showLocationList[0].dictValue
          } else {
            this.ruleForm.locationType = this.locationType
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    this.getStatusList()
    this.id = this.dialogData.id
    if (this.id) {
      this.isAdd = this.dialogData.type === 'copy' ? true : false
      this.firstEnter = true
      this.getFormData()
    } else {
      this.isAdd = true
    }
  },
  methods: {
    async getStatusList() {
      // 显示终端
      // this.terminalTypeList = await sysNormalDisable(
      //   'advertising_spaces_terminal'
      // )
      // 位置
      // let data = await sysNormalDisable('advertising_spaces_location')
      // let data = await sysNormalDisable('advertising_space_list')
      const [terminalTypeList, spaceList, collegeList] = await Promise.all([
        sysNormalDisable('advertising_spaces_terminal'),
        sysNormalDisable('advertising_space_list'),
        sysNormalDisable('sys_college', 'collegeType')
      ])
      this.terminalTypeList = terminalTypeList
      this.allLocationList = [...spaceList]
      this.collegeList = collegeList
      let pcData = []
      let h5Data = []
      let appData = []
      this.allLocationList.forEach((item) => {
        if (item.dictLabel === 'PC') {
          pcData.push(item)
        }
        if (item.dictLabel === 'H5') {
          h5Data.push(item)
        }
        if (item.dictLabel === 'APP') {
          appData.push(item)
        }
      })
      this.h5LocationList = [...h5Data]
      this.pcLocationList = [...pcData]
      this.appLocationList = [...appData]
      if (this.dialogData.type === 'add') {
        this.setDefaultData()
      }
    },
    /*设置默认值*/
    setDefaultData() {
      this.ruleForm.terminalType = this.terminalTypeList[0].dictValue
      //位置的初始默认值，在watch里赋
      // this.ruleForm.locationType = this.showLocationList[0].dictValue
    },
    //封面图设置
    getImgUrl(url) {
      this.ruleForm.imgInfo = url
    },
    //弹窗图设置
    getOpenerUrl(url) {
      this.ruleForm.imgPopup = url
    },
    /* 编辑时获取表单详情 */
    getFormData() {
      getDetail(this.id, (response) => {
        let {
          terminalType,
          locationType,
          name,
          description,
          imgInfo,
          collegeId,
          courseType,
          url,
          channelIds,
          imgPopup
        } = response
        this.ruleForm = {
          terminalType,
          locationType,
          name,
          description,
          imgInfo,
          collegeId,
          courseType,
          url,
          channelIds,
          imgPopup
        }
      })
    },
    /* 确认提交 */
    confirmLabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          let obj = { ...this.ruleForm }
          if (obj.terminalType !== 'APP') {
            obj.courseType = null
            obj.collegeId = []
          }
          if (obj.terminalType !== 'H5') {
            // obj.channelIds = null
            obj.imgPopup = null
            if (obj.locationType !== 'LIVE' && obj.courseType !== 'FORMAL') {
              obj.channelIds = ''
            }
          }
          if (this.isAdd) {
            // 新增/一键复制
            add(
              obj,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning({
                  message: response.message,
                  type: 'warning'
                })
              }
            )
          } else {
            // 编辑
            edit(
              this.id,
              obj,
              (response) => {
                this.loading = false
                this.$emit('refresh')
                this.cancelLabel()
              },
              (response) => {
                this.loading = false
                this.$message.warning({
                  message: response.message,
                  type: 'warning'
                })
              }
            )
          }
        } else {
          return false
        }
      })
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.id = null
      this.dialogData.type = ''
      this.dialogData.isShow = false
    },
    clearValidate(formName) {
      this.$refs[formName].clearValidate()
    },
    handleChangeTerminalType(val) {
      if (val === 'APP' && !this.ruleForm.courseType) {
        this.ruleForm.courseType = 'EXPERIENCE'
      }
      this.clearValidate('ruleForm')
    }
  },
  computed: {
    /*
      1.显示终端选中PC时,位置为直播间广告位(LIVE),显示频道号
      2.显示终端选中H5时,默认显示频道号
      3.显示终端选中APP时,课程为正式课(FORMAL)，显示频道号
    */
    isShowChannelIds() {
      if (
        this.ruleForm.terminalType === 'PC' &&
        this.ruleForm.locationType === 'LIVE'
      ) {
        return true
      } else if (this.ruleForm.terminalType === 'H5') {
        return true
      } else if (
        this.ruleForm.terminalType === 'APP' &&
        this.ruleForm.courseType === 'FORMAL'
      ) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>

<style lang="less">
#dialogAdPosition {
  .el-textarea {
    .el-textarea__inner {
      height: 70px;
      padding-bottom: 18px;
    }
    .el-input__count {
      display: inline-block;
      color: #909399;
      background: #fff;
      position: absolute;
      width: calc(100% - 10px);
      font-size: 12px;
      bottom: 1px;
      right: 1px;
      left: 1px;
      text-align: right;
      line-height: 20px;
    }
  }
}
.el-select-dropdown.el-popper.position {
  li.el-select-dropdown__item {
    span {
      white-space: pre;
    }
  }
}
</style>
